import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { zip } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';

import { I18NService } from '../i18n/i18n.service';
import { SettingsService } from '../settings/settings.service';
import { SystemService } from '../system/system.service';
import { SystemUserService } from '../system/system-user.service';
import { TokenService } from '../auth/token/token.service';

import { check } from '../auth/token/utils';
import { Constant } from '../constant';

/**
 * 用于应用启动时
 * 一般用来获取应用所需要的基础数据等
 */
@Injectable()
export class StartupService {
  constructor(
    private translate: TranslateService,
    private i18nService: I18NService,
    private settingService: SettingsService,
    private httpClient: HttpClient,
    private systemService: SystemService,
    private systemUserService: SystemUserService,
    private tokenService: TokenService
  ) { }

  init(): Promise<any> {
    // only works with promises
    // https://github.com/angular/angular/issues/15088
    return new Promise((resolve, reject) => {
      zip(
        this.httpClient.get(`assets/i18n/${this.i18nService.defaultLang}.json`),
        this.httpClient.get('assets/app-data.json'),
      )
        .pipe(
          // 接收其他拦截器后产生的异常消息
          catchError(([langData, appData]) => {
            return [langData, appData];
          }),
      )
        .subscribe(
          ([langData, appData]) => {
            // setting language data
            this.translate.setTranslation(this.i18nService.defaultLang, langData);
            this.translate.setDefaultLang(this.i18nService.defaultLang);
            this.settingService.setLayout('lang', this.i18nService.defaultLang);

            // application data
            const res: any = appData;
            // 应用信息：包括站点名、描述、年份
            this.settingService.setApp(res.app);
            if (check(this.tokenService.get())) {
              this.load();
            }
          },
          () => { },
          () => {
            resolve(null);
          },
      );
    });
  }

  load(): void {
    // 初始化菜单
    this.systemService.getMenus().subscribe(res => {
      this.systemService.addMenu(res);
    });
    // 用户信息：包括姓名、头像、邮箱地址
    if (!localStorage.getItem(Constant.USER_KEY)) {
      this.systemUserService.getUserInfo().subscribe(res => {
        this.settingService.setUser(res);
      });
    }
  }
}
